import { PlusBase } from "./plus/PlusBase";
import { EventEmitter } from "events";
import { IGlobal } from "./entity/Global";
declare var global: IGlobal;
export class PlusMgr extends EventEmitter {
    private _hash: any;
    private _list: string[];
    constructor() {
        super();
        this._hash = {};
        this._list = [];
    }

    registPlus(plus: PlusBase) {
        if (!this._hash[plus.name]) {
            this._hash[plus.name] = plus;
            this._list.push(plus.name);
        }
    }

    start() {
        this._initNext();
    }

    private _initNext() {
        if (this._list.length > 0) {
            let plus = this.getPlus(this._list.shift());
            plus.once("complete", this._complete.bind(this, plus.name));
            plus.init();
        } else {
            global.log.info("all plus init complete");
            this.emit("complete");
        }
    }

    private _complete(plusName: string) {
        global.log.info(plusName + " init complete");
        this._initNext();
    }

    getPlus(type: string): PlusBase
    getPlus<T>(type: { NAME: string, new(...arg): T }): T
    getPlus(...arg): PlusBase {
        if(typeof arg[0] =="string"){
            return this._hash[arg[0]];
        }else if(arg[0].NAME){
            return this._hash[arg[0].NAME];
        }
        return null;
    }
}